// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database({
  throwOnNotFound: false
});
const _ = db.command;
const myOrbit = db.collection("myOrbit");
const suffererOrbit = db.collection("suffererOrbit");
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  var id = event.id;
  var my = await myOrbit.doc(id).get();
  var result ={}
  result["empty"] =true;
  result["my"] = {};
  result["sufferer"] =[];
  if (my.data == null)
    {return  result;}
  else{
    result["empty"] =false;
    result["my"] = my.data;
    //这里我们认为超不过100条，如果有这种情况再作处理
    var sufferer = await suffererOrbit.where({
        city:my.data.city,
        date:my.data.date,
        location: _.geoNear({
          geometry: db.Geo.Point(my.data.location.longitude, my.data.location.latitude),
          maxDistance: 1000,
        })
      }).get();
    result["sufferer"] = sufferer.data;
    if (sufferer.data.length == 0){
      await myOrbit.doc(id).update({
        data:{
          dangerous:false
        }
      })
    }else{
      await myOrbit.doc(id).update({
        data:{
          dangerous:true
        }
      })
    }
    return result;
  }
}